package com.zhipu.balance.ui.home.calculate.rice

import android.os.Bundle
import android.text.TextUtils
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.constant.TimeConstants
import com.blankj.utilcode.util.*
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.sjl.scanner.UsbKeyboardAutoScan
import com.zhipu.balance.R
import com.zhipu.balance.databinding.ActivityRiceBinding
import com.zhipu.balance.listener.AddNumberOnClickListener
import com.zhipu.balance.listener.AddOnClickListener
import com.zhipu.balance.mobile.event.*
import com.zhipu.balance.mobile.temporaryClass.UniqueInfoById
import com.zhipu.balance.pop.NumberPopup
import com.zhipu.balance.ui.BaseActivity
import com.zhipu.balance.ui.home.calculate.adapter.ProfitOrderAdapter
import com.zhipu.balance.ui.home.calculate.corn.CornActivity
import com.zhipu.balance.ui.home.calculate.dami.DaMiActivity
import com.zhipu.balance.ui.home.calculate.rapeseed.RapeseedActivity
import com.zhipu.balance.ui.home.calculate.soybean.SoybeanActivity
import com.zhipu.balance.ui.home.calculate.wheat.WheatActivity
import com.zhipu.balance.ui.vm.home.calculate.rice.RiceViewModel
import com.zhipu.balance.utils.InitializeUtils
import com.zhipu.balance.utils.dialog.CommonDialog
import com.zhipu.balance.utils.request.InterfaceRequestUtils

/**
 * 功能计算-稻谷
 */
class RiceActivity : BaseActivity<ActivityRiceBinding>() {
    /**
     * VM
     */
    private var mRiceViewModeel: RiceViewModel? = null

    /**
     * 类型
     */
    private var productCategoryText : String? = null


    /**
     * usb键盘模式扫码示例，无需EditText接收,推荐
     */
    private val usbKeyboardAutoScan: UsbKeyboardAutoScan = UsbKeyboardAutoScan()



    override fun initCreate() {
        super.initCreate()
        InitializeUtils.AppComponent()?.doInjectionMain(this)
        mRiceViewModeel = ViewModelProvider(this, viewModelFactory)[RiceViewModel::class.java]
    }


    override fun initParam() {
        super.initParam()
        productCategoryText = intent.getStringExtra("ProductCategoryText");
        println(productCategoryText)
    }


    /**
     * 初始化根布局
     *
     * @return 布局layout的id
     */
    override fun initContentView(savedInstanceState: Bundle?): Int {
        return R.layout.activity_rice
    }


    override fun initView() {
        super.initView()
        binding.viewModel = mRiceViewModeel

        binding.rv.layoutManager = LinearLayoutManager(mContext)
        binding.rv.adapter = mRiceViewModeel?.mRiceAdapter
    }

    override fun initViewObservable() {
        super.initViewObservable()
        /**
         * Fragment回调
         */
        mRiceViewModeel!!.mFragments.observe(this, Observer{ t ->
            var mProfitOrderAdapter = ProfitOrderAdapter(supportFragmentManager,t!!)
            binding.NoScrollViewPager.adapter = mProfitOrderAdapter
        })
        /**
         * 位置
         */
        mRiceViewModeel!!.mPosition.observe(this,Observer{
            binding.NoScrollViewPager.currentItem = it
        })
        binding.NoScrollViewPager.setNoScroll(true);
        /**
         * 扫描枪回调
         */
        usbKeyboardAutoScan.setOnScanListener {
            InterfaceRequestUtils.getUniqueInfoById(it,object : AddOnClickListener {
                override fun onSkipClicked(sKip: String?) {
                    if(!TextUtils.isEmpty(sKip)){
                        var mUniqueInfoById = GsonUtils.fromJson(sKip,UniqueInfoById::class.java)
                        if(null != mUniqueInfoById){
                            when(mUniqueInfoById.productCategoryText){
                                "稻谷" -> {
                                    mRiceViewModeel?.UpdatePage(it)
                                }
                                "小麦" -> {
                                    //小麦
                                    var mBundle = Bundle()
                                    mBundle.putString("ProductCategoryText",mUniqueInfoById.productCategoryText)
                                    ActivityUtils.startActivity(WheatActivity::class.java,mBundle)
                                }
                                "玉米" -> {
                                    //玉米
                                    var mBundle = Bundle()
                                    mBundle.putString("ProductCategoryText",mUniqueInfoById.productCategoryText)
                                    ActivityUtils.startActivity(CornActivity::class.java,mBundle)
                                }
                                "大米" -> {
                                    //大米
                                    var mBundle = Bundle()
                                    mBundle.putString("ProductCategoryText",mUniqueInfoById.productCategoryText)
                                    ActivityUtils.startActivity(DaMiActivity::class.java,mBundle)
                                }
                                "大豆" -> {
                                    //大豆
                                    var mBundle = Bundle()
                                    mBundle.putString("ProductCategoryText",mUniqueInfoById.productCategoryText)
                                    ActivityUtils.startActivity(SoybeanActivity::class.java,mBundle)
                                }
                                "油菜籽" -> {
                                    //油菜籽
                                    var mBundle = Bundle()
                                    mBundle.putString("ProductCategoryText",mUniqueInfoById.productCategoryText)
                                    ActivityUtils.startActivity(RapeseedActivity::class.java,mBundle)
                                }
                                else -> {
                                    mRiceViewModeel?.UpdatePage(it)
                                }
                            }
                        }
                    }else{
                        mRiceViewModeel?.UpdatePage(it)
                    }
                }
            })
        }
        /**
         * 编号
         */
        binding.ETNumber.setOnEditorActionListener(object : TextView.OnEditorActionListener{
            override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
                when(actionId){
                    EditorInfo.IME_ACTION_DONE ->{
                        if(!TextUtils.isEmpty(mRiceViewModeel?.mNumber?.get())) {
                            val mNumberPopup = NumberPopup("稻谷", mRiceViewModeel?.mNumber?.get(),object : AddNumberOnClickListener{
                                override fun <T> onSkipClicked(position: Int, item: T) {
                                    var mRecordRice = item as RecordRice
                                    mRiceViewModeel?.updatePage(mRecordRice)
                                }
                            })
                            XPopup.Builder(ActivityUtils.getTopActivity())
                                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                                .autoOpenSoftInput(false)
                                .asCustom(mNumberPopup)
                                .show();
                        }
                    }
                }
                return false
            }
        })
    }


    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
        val defaultEd = SPUtils.getInstance().getString("SerialNumber")
        if (defaultEd == "扫码枪") {
            if (usbKeyboardAutoScan.isIntercept && event!!.keyCode != KeyEvent.KEYCODE_BACK) { //不处理返回键
                usbKeyboardAutoScan.analysisKeyEvent(event)
                return true //防止输入框接收事件
            }
        }
        return super.dispatchKeyEvent(event)
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev!!.action == MotionEvent.ACTION_DOWN) {
            val v = currentFocus
            if (isShouldHideKeyboard(v, ev)) {
                //隐藏软键盘
                KeyboardUtils.hideSoftInput(binding.NoScrollViewPager)
            }
        }
        return super.dispatchTouchEvent(ev)
    }

}